// const Promise = require('../polyfill/es6-promise.js').Promise;
let util = require('../utils/util.js');
let common = require('../utils/common.js');

function getData(res) {
	if (!res.data) return;
	let data = res.data;
	if (data && data.hasOwnProperty("result") && data.result && data.result.hasOwnProperty("current_page")) {
		return {
			msg: data.message,
			result: data.code === 20000 ? 'success' : 'fail',
			results: data.result.data,
			next: Number(data.result.last_page) - Number(data.result.current_page),
			count: data.result.total,
			code: data.code,
			pageCount: data.result.per_page
		}
	} else if (data.hasOwnProperty('code')) {
		return {
			msg: data.message,
			result: data.code === 20000 ? 'success' : 'fail',
			results: data.result,
			code: data.code
		}
	} else {
		return {
			result: "success",
			results: data,
		}
	}
}


function promisify() {
	uni.pro = {}; // uni.pro 下面挂载着返回 promise 的 uni.API
	// 普通的要转换的函数
	const functionNames = [
		'login',
		'getUserInfo',
		'navigateTo',
		'checkSession',
		'getStorageInfo',
		'removeStorage',
		'clearStorage',
		'getNetworkType',
		'getSystemInfo',
		'chooseImage', //选择图片
		'uploadFile', //上传图片,
		'chooseLocation', //选择地址,
		'getImageInfo',
		'requestPayment',
		'getLocation',
		'downloadFile',
		'saveImageToPhotosAlbum',
		"saveVideoToPhotosAlbum"
	];

	functionNames.forEach((fnName) => {
		uni.pro[fnName] = (obj = {}) => new Promise((resolve, reject) => {
			obj.success = function(res) {
				//console.log(`uni.${fnName} success`, res)
				resolve(res);
			};
			obj.fail = function(err) {
				//console.error(`uni.${fnName} fail`, err);
				uni.hideLoading();
				reject(err);
			};
			wx[fnName](obj);
		});
	});

	uni.pro.fromSync = (fun) => new Promise((resolve, reject) => {
		try {
			resolve(fun());
		} catch (ex) {
			reject(ex);
		}
	});

	uni.pro.all = (arr) => Promise.all(arr);
	// 特殊改造的函数

	uni.pro.getStorage = (key) => new Promise((resolve, _reject) => {
		uni.getStorage({
			key,
			success: (res) => {
				resolve(res.data); // unwrap data
			},
			fail: (_err) => {
				resolve(); // not reject, resolve undefined
			}
		});
	});

	uni.pro.setStorage = (key, value) => new Promise((resolve, reject) => {
		uni.setStorage({
			key,
			data: value,
			success: (_res) => {
				resolve(value); // 将数据返回
			},
			fail: (err) => {
				reject(err);
			}
		});
	});

	uni.pro.request = (options, isLoad = 0) => {
		let url = uni.getStorageSync('serverurl');
		url += options.url
		return new Promise((resolve, reject) => {
			//console.log(url);
			let req = {
				url: url,
				method: options.method || 'GET',
				header: {
					Auth: 'Bearer ' + uni.getStorageSync("token"),
					Accept: 'application/json, text/plain, */*'
				},
				success: (res) => {
					if (res.data) {
						if (res.data.code) {
							if (res.data.code == 65001) {
								resolve({
									result: 'fail',
									msg: '请求失败！',
									code: 401
								});
							} else {
								resolve(getData(res))
							}
						} else {
							resolve(getData(res))
						}
					} else {
						resolve({
							result: 'fail',
							msg: '请求失败！',
							code: res.statusCode
						});
					}
				},
				fail: (err) => {
					console.log(err)
					resolve({
						result: 'fail',
						msg: '请求失败！',
						code: 500
					});
				}
			};
			if (options.data) {
				req.data = options.data;
				req.header['content-type'] = 'application/json';
			}
			uni.request(req);
		});
	};
}

promisify();

module.exports = Promise;